import React from "react";
import { Route, NavLink, Switch, withRouter, Redirect } from "react-router-dom";

import Header from "./components/Header";
import Home from "./pages/Home/index";
import About from "./pages/About";
import Help from "./pages/Help";
import Detail from "./pages/Detail";
import Login from "./pages/Login";

function App() {
  return (
    <div className="app">
      <Header a="1" b="2" />
      <div className="main">
        <div className="left">
          <NavLink className="link" to="/home" activeClassName="hello">
            Home
          </NavLink>
          <NavLink className="link" to="/about" activeClassName="hello">
            About
          </NavLink>
          <NavLink className="link" to="/help" activeClassName="hello">
            Help
          </NavLink>
        </div>
        <div className="right">
          <Switch>
            <Route path="/home" component={Home} />
            <Route
              path="/about"
              render={(props) => {
                // 做一些判断
                const token = window.localStorage.getItem("token");
                if (token) {
                  // 存在，就正常显示 About
                  return <About {...props} />;
                } else {
                  // 不存在，就直接打到 /login 登录页面
                  // 渲染 Redirect 组件, Redirect 是一种 replace 模式
                  return <Redirect to="/login?redirect=/about" />;
                }
              }}
            />
            <Route
              path="/help"
              render={(props) => {
                // 做一些判断
                const token = window.localStorage.getItem("token");
                if (token) {
                  // 存在，就正常显示 Help
                  return <Help {...props} />;
                } else {
                  // 不存在，就直接打到 /login 登录页面
                  // 渲染 Redirect 组件
                  return <Redirect to="/login?redirect=/help" />;
                }
              }}
            />
            <Route path="/detail/:id" component={Detail} />
            <Route path="/login" component={Login} />
          </Switch>
        </div>
      </div>
    </div>
  );
}

export default withRouter(App);
